package cn.vinann.demo.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.mail.internet.MimeMessage;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.freemarker.FreeMarkerAutoConfiguration.FreeMarkerWebConfiguration;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import freemarker.template.Template;

/**
 * 邮件
 * @author wn
 *
 */
@RestController
@RequestMapping("/mail")
public class MailController {

	
	@Autowired
	private JavaMailSender mailSender;
	
	@Autowired
	private FreeMarkerWebConfiguration freeMarkerConfigurer;
	
	@RequestMapping("")
	public String mail(){
		
		try {
			//普通邮件
			SimpleMailMessage simpleMessage = new SimpleMailMessage();
			simpleMessage.setBcc("vinann@163.com");
			simpleMessage.setCc("vinann@163.com");
			simpleMessage.setFrom("vinann@163.com");
			simpleMessage.setReplyTo("vinann@163.com");
			simpleMessage.setSentDate(new Date());
			simpleMessage.setSubject("subject");
			simpleMessage.setText("text");
			simpleMessage.setTo("weinan@akcomesh.com");
			mailSender.send(simpleMessage);
			
			//模板邮件
			MimeMessage mimeMessage = mailSender.createMimeMessage();

			MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
			
			helper.setFrom("vinann@163.com");//发送者.
			helper.setTo("weinan@akcomesh.com");//接收者.
			helper.setSubject("模板邮件（邮件主题）");//邮件主题.

			Map<String, Object> model = new HashMap<String, Object>();
			model.put("username", "Vinann");
			
			
			Template template = freeMarkerConfigurer.freeMarkerConfigurer().getConfiguration().getTemplate("email.ftl");//加载资源文件  
			
			String html = FreeMarkerTemplateUtils.processTemplateIntoString(template, model);
			helper.setText(html, true);

			mailSender.send(mimeMessage);
		}  catch (Exception e) {
			e.printStackTrace();
		}
		
		return "发送成功！";
	}
	
}
